<template>
  <div class="main">
    <breadcrumb/>
    <el-button type="primary" @click="openDialog(true)">添加角色</el-button>
    <el-table :data="roleList" stripe border>
      <el-table-column label="#" type="expand" header-align="center" align="center">
        <template slot-scope="scope">
          <el-row
            v-for="(item1,i1) in scope.row.children"
            :key="item1.id"
            :class="['vcenter','bdbottom',i1 === 0 ? 'bdtop' : '']"
          >
            <el-col :span="5">
              <el-tag closable @close="removeRightById(scope.row,item1.id)">{{item1.authName}}</el-tag>
              <i class="el-icon-caret-right"></i>
            </el-col>
            <el-col :span="19">
              <el-row
                v-for="(item2,i2) in item1.children"
                :key="item2.id"
                :class="[i2 === 0 ? '' : 'bdtop','vcenter']"
              >
                <el-col :span="6">
                  <el-tag type="success" closable @close="removeRightById(scope.row,item2.id)">{{item2.authName}}
                  </el-tag>
                  <i class="el-icon-caret-right"></i>
                </el-col>
                <el-col :span="18">
                  <el-tag
                    type="warning"
                    v-for="item3 in item2.children"
                    :key="item3.id"
                    class="tagright"
                    closable
                    @close="removeRightById(scope.row,item3.id)"
                  >{{item3.authName}}
                  </el-tag>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </template>
      </el-table-column>
      <el-table-column label="#" type="index" header-align="center" align="center"></el-table-column>
      <el-table-column prop="roleName" label="角色名称" header-align="center" align="center"></el-table-column>
      <el-table-column prop="roleDesc" label="角色描述" header-align="center" align="center"></el-table-column>
      <el-table-column label="操作" header-align="center" align="center">
        <template slot-scope="scope">
          <el-button type="primary" class="el-icon-edit" size="mini"
                     @click="openDialog(false,scope.row.id)">编辑角色
          </el-button>
          <el-button type="danger" class="el-icon-delete" size="mini" @click="deleteRole(scope.row.id)">删除</el-button>
          <el-button type="warning" class="el-icon-setting" size="mini"
                     @click="openAuthorizeDialog(scope.row)">分配权限
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--添加角色弹窗-->
    <el-dialog
      :title="isAdd ? '添加角色' : '修改角色信息'"
      :visible.sync="addRoleDialogVisible"
      width="50%"
      @close="handleAddRoleDialogClose"
      :close-on-click-modal="false"
    >
      <el-form :model="addForm" label-width="100px" ref="addFormRef">
        <el-form-item label="角色名称" prop="roleName" :rules="[{required:true,message:'请输入角色名称'}]">
          <el-input v-model="addForm.roleName" placeholder="输入角色名称"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
          <el-button @click="addRoleDialogVisible = false">取 消</el-button>
          <el-button v-if="isAdd" type="primary" @click="addRole">确定</el-button>
          <el-button v-else type="primary" @click="modifyRoleInfo">确认修改</el-button>
        </span>
    </el-dialog>

    <!--角色授权弹窗-->
    <el-dialog
      title="角色授权"
      :visible.sync="roleAuthorizeDialogVisible"
      :close-on-click-modal="false"
      class="scroll_dialog"
    >
      <el-tree
        :data="allRights"
        :props="roleRightsProps"
        default-expand-all
        show-checkbox
        node-key="id"
        :default-checked-keys="defaultCheckRights"
        ref="roleRightsRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
          <el-button @click="roleAuthorizeDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveRoleRightsInfo">保存授权信息</el-button>
        </span>
    </el-dialog>
  </div>
</template>

<script>
  import Breadcrumb from './../../components/Breadcrumb'
  import {
    addRole,
    deleteRole,
    getRoleInfoById,
    getRoles,
    modifyRoleInfo,
    removeRightById,
    saveRoleRightsInfo
  } from '../../api/right/roles'
  import {getRights} from '../../api/right/rights'

  export default {
    name: 'Roles',
    components: {Breadcrumb},
    data: () => {
      return {
        roleList: [],
        addRoleDialogVisible: false,
        roleAuthorizeDialogVisible: false,
        addForm: {
          roleId: 0,
          roleName: '',
          roleDesc: ''
        },
        isAdd: false,
        allRights: [],
        roleRightsProps: {
          children: 'children',
          label: 'authName'
        },
        defaultCheckRights: [],
        currentRole: {}
      }
    },
    created() {
      this.getRoles()
    },

    methods: {
      // 保存授权信息
      async saveRoleRightsInfo() {
        const rids = [...this.$refs.roleRightsRef.getCheckedKeys(), ...this.$refs.roleRightsRef.getHalfCheckedKeys()]
        const {data: res} = await saveRoleRightsInfo(this.currentRole.id, rids.join(','))
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        await this.getRoles()
        this.roleAuthorizeDialogVisible = false
      },

      // 打开角色授权弹窗
      async openAuthorizeDialog(role) {
        this.currentRole = role
        this.defaultCheckRights = this.handlerCheckNode(role.children, []).map(item => item.id)
        const {data: res} = await getRights()
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.allRights = res.data
        this.roleAuthorizeDialogVisible = true
      },

      // 递归求出选中的树节点
      handlerCheckNode(children, nodeList) {
        if (children !== undefined) {
          children.map(child => {
            if (child.children === undefined) {
              nodeList.push(child)
            }
            this.handlerCheckNode(child.children, nodeList)
          })
        }
        return nodeList
      },

      // 修改角色信息
      async modifyRoleInfo() {
        const {data: res} = await modifyRoleInfo(this.addForm.roleId, this.addForm)
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success('修改角色信息成功')
        await this.getRoles()
        this.addRoleDialogVisible = false
      },

      // 打开弹窗
      async openDialog(flag, roleId) {
        if (flag) {
          this.isAdd = true
          this.addRoleDialogVisible = true
        } else {
          const {data: res} = await getRoleInfoById(roleId)
          if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
          this.isAdd = false
          this.addForm = res.data
          this.addRoleDialogVisible = true
        }
      },

      // 删除角色
      async deleteRole(roleId) {
        const r = await this.$confirm('确定要删除该角色？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err)
        if (r !== 'confirm') return this.$message.info('已取消删除！')
        const {data: res} = await deleteRole(roleId)
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        await this.getRoles()
      },

      // 添加角色
      addRole() {
        this.$refs.addFormRef.validate(async valid => {
          if (!valid) return
          const {data: res} = await addRole(this.addForm)
          if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
          this.$message.success(res.meta.msg)
          await this.getRoles()
          this.addRoleDialogVisible = false
        })
      },

      // 关闭添加角色对话框
      handleAddRoleDialogClose() {
        this.$refs.addFormRef.resetFields()
      },

      // 删除角色的权限
      async removeRightById(role, rightId) {
        const r = await this.$confirm('确定取消角色的该权限？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err)
        if (r !== 'confirm') return this.$message.info('已取消删除')
        const {data: res} = await removeRightById(role.id, rightId)
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        role.children = res.data
      },

      // 获取角色列表数据
      async getRoles() {
        const {data: res} = await getRoles()
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.roleList = res.data
      }
    }
  }
</script>
<style lang="less" scoped>
  @import "./index";
</style>
